package com.wedata.tikhub;

import com.alibaba.fastjson2.JSON;
import com.aliyun.oss.ServiceException;
import com.disdr.utils.DateUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 第三方平台基础类
 * https://docs.tikhub.io/
 *
 * 登录后台管理平台：
 * https://user.tikhub.io/zh-hans/users/signin
 * 账号：@qq.com
 * 密码：锁屏密码，9位
 */
public class TikhubBase {

    //public static final String BASE_URL = "https://api.tikhub.io/";
    //换新域名，速度更快
    public static final String BASE_URL = "https://api.tikhub.dev/";

    //刘欣晟的账号
    //public static final String TOKEN = "Bearer 9KAHW0F7yCQUvDYK1lGyu3lt6TxSpq3U4adYmBfFlGFZ6G80J9ls3RC2Jg==";
    //我的账号，初始免费额度：$0.0072 -> 邮箱认证后 $0.0572 -> 调了一次接口后 $0.0562 -> 调了两次接口后 $0.0552
    public static final String TOKEN = "Bearer 0KIEX9wP0EyEvXafNpmOwiTccxmgfrw5vQDbtESsTNGDjmqAIi2eXCC4HQ==";

    public static Map<String, String> getTokenHeader(){
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", TOKEN);
        headers.put("Accept", "*/*");
        headers.put("Connection", "keep-alive");
        return headers;
    }

    public static String doGet(String url){
        try {
            OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(20, TimeUnit.SECONDS).build();
            // 设置超时时间
            Request request = new Request.Builder()
                    .url(url)
                    .method("GET",null)
                    .addHeader("Authorization", TOKEN)
                    .addHeader("Accept", "*/*")
                    //.addHeader("Connection", "keep-alive")
                    .build();
            Response response = client.newCall(request).execute();
            if (response.code() != 200 || Objects.isNull(response.body())){
                throw new ServiceException("tikhub调用异常 resp=>" + JSON.toJSONString(response));
            }
            return response.body().string();
        } catch (ServiceException | IOException e) {
            System.out.println("tikhub调用异常" + e);
        }
        return null;
    }

    public static String timeToStr(int time){
        long timeMillis = time*1000L;
        Date date = new Date(timeMillis);
        return DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",date);
    }

}
